const dateformat = require('dateformat')


function page(req, res, next) {
  const n = req.query
  const filter = {
    limit: parseInt(n.limit) || 10,
    page: parseInt(n.page) || 1,
    sort: n.sort || 'meet_day',
    by: parseInt(n.by) || -1,
    start: n.start || false,
    end: n.end || false,
    file: n.file || false,
    school: n.school || 'kmust',
  }
  req.filter = {
    limit: Math.abs(filter.limit),
    page: Math.abs(filter.page),
    sort: {},
    filter: {},
    file: filter.file,
    school: filter.school,
  }
  if (filter.start && filter.end) {
    try {
      const start = dateformat(filter.start, 'yyyy-mm-dd')
      const end = dateformat(filter.end, 'yyyy-mm-dd')
      if (filter.school === 'kmust') {
        Object.assign(req.filter.filter, {
          meet_day: {
            $gte: start,
            $lte: end,
          }
        })
        req.filter.sort[filter.sort] = filter.by
      } else {
        // 云大的需要时间
        Object.assign(req.filter.filter, {
          date: {
            $gte: start,
            $lte: end,
          }
        })
        req.filter.sort['date'] = filter.by
      }
    } catch (e) {
    }
  }
  next()
}

module.exports = page
